package com.mcc.app.common.impl;

import com.mcc.app.common.IHttpCallService;
import com.mcc.common.core.domain.AjaxResult;
import com.mcc.common.exception.CustomException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestClientException;
import org.springframework.web.client.RestTemplate;

import java.util.HashMap;
import java.util.Map;

@Service
public class HttpCallServiceImpl implements IHttpCallService {

    @Autowired
    private RestTemplate restTemplate;

    @Override
    public AjaxResult getForMap(String url, Map<String, Object> param) {
        try {
            int count = 0;
            for (Map.Entry<String, Object> entry : param.entrySet()) {
                if (count == 0) {
                    url += "?";
                } else {
                    url += "&";
                }
                url += entry.getKey() + "=" + entry.getValue();
                count++;
            }
            return restTemplate.getForObject(url, AjaxResult.class);
        } catch (RestClientException e) {
//            e.printStackTrace();
            throw new CustomException("数采服务无法连接");
        }
    }

    @Override
    public AjaxResult postForMap(String url, Map<String, Object> param) {
        try {
            if (param == null) param = new HashMap<>();
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_JSON);
            HttpEntity<Map<String, Object>> request = new HttpEntity<>(param, headers);
            return restTemplate.postForObject(url, request, AjaxResult.class);
        } catch (RestClientException e) {
//            e.printStackTrace();
            throw new CustomException("数采服务无法连接");
        }
    }
}
